<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card >
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入搜索内容" v-model="queryUserListinfo.query"
          clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :data="userList"
        border
        stripe
        fit
       >
        <el-table-column
          type="index"
          label="#"
          >
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
   >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
     >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          >
        </el-table-column>
         <el-table-column
          prop="role_name"
          label="角色"
       >
        </el-table-column>
         <el-table-column
          prop="mg_state"
          label="状态"
          >
          <template v-slot='slotProps'>
            <el-switch v-model="slotProps.row.mg_state" @change="editUserState(slotProps.row)"></el-switch>
          </template>
        </el-table-column>
         <el-table-column
          label="操作"
          min-width="180"

       >
          <template v-slot="slotProps">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditUserInfo(slotProps.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(slotProps.row.id)"></el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDailog(slotProps.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryUserListinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryUserListinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户会话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%" @close="addUserDialogClosed">
      <!-- 内容区域 -->
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      <!-- 表单底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">添 加</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息会话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editUserInfoDialogVisible"
      width="50%" @close="editUserDialogClosed">
      <!-- 内容区域 -->
        <el-form :model="editUserInfoForm" :rules="editUserInfoFormRules" ref="editUserInfoFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserInfoForm.username"   :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserInfoForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="editUserInfoForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      <!-- 表单底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserInfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">修 改</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色会话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRloeDialogVisible"
      width="50%">
      <!-- 内容区域 -->
       <div>
         <p>用户名: {{ setRole.username }}</p>
         <p>角色: {{ setRole.role_name }}</p>
       </div>
       <span>分配角色：</span>
       <el-select v-model="selectedRoleId"  placeholder="请选择">
          <el-option
            v-for="item in setRoleInfo"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      <!-- 表单底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRloeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRloe()">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => { // 邮箱验证规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule, value, cb) => { // 邮箱验证规则
      const regMbile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMbile.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryUserListinfo: { // 查询用户列表信息需要传递的参数对象
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [], // 获取到的用户列表数据
      total: 0, // 用户数据总数
      addUserDialogVisible: false, // 控制添加用户会话框的显示和隐藏
      addUserForm: { // 添加用户需要传递的参数对象
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [// 用户名验证规则
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [// 密码验证规则
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserInfoDialogVisible: false, // 控制修改用户信息会话框都的显示和隐藏
      editUserInfoForm: { // 修改用户信息需要的数据对象
        id: '',
        email: '',
        mobile: '',
        username: ''
      },
      editUserInfoFormRules: { // 修改用户信息会话框中的验证规则
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRloeDialogVisible: false, // 控制分配角色会话框的显示和隐藏
      setRole: { // 分配角色会话框框需要用到的数据，包括用户id

      },
      setRoleInfo: { // 分配角色下拉框框需要用到的数据

      },
      selectedRoleId: '' // 下拉框选中的id
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () { // 获取用户列表
      const { data: res } = await this.$http.get('users', { params: this.queryUserListinfo })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.message)
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleCurrentChange (val) { // 当前页
      this.queryUserListinfo.pagenum = val
      this.getUserList()
    },
    handleSizeChange (val) { // 每页数据条数
      console.log(val)
      this.queryUserListinfo.pagesize = val
      this.getUserList()
    },
    async editUserState (userInfo) { // 监听 switch 开关 change 事件 更新用户状态
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$msg.error('更新用户状态失败！')
      }
      this.$msg.success('更新用户状态成功！')
    },
    addUserDialogClosed () { // 监听添加用户对话框关闭事件
      this.$refs.addUserFormRef.resetFields()
    },
    addUser () { // 添加用户
      this.$refs.addUserFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          console.log(res)
          if (res.meta.status === 201) {
            this.addUserDialogVisible = false
            this.$msg.success('添加用户成功')
          }
          this.getUserList()
        }
      })
    },
    async showEditUserInfo (id) { // 显示修改用户信息对话框
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$msg.error('获取用户信息失败')
      this.editUserInfoDialogVisible = true
      this.editUserInfoForm.id = res.data.id
      this.editUserInfoForm.email = res.data.email
      this.editUserInfoForm.mobile = res.data.mobile
      this.editUserInfoForm.username = res.data.username
    },
    editUserDialogClosed () { // 修改用户信息会话框关闭，重置表单验证
      this.$refs.editUserInfoFormRef.resetFields()
    },
    editUserInfo () { // 修改用户信息
      this.$refs.editUserInfoFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUserInfoForm.id, {
          email: this.editUserInfoForm.email,
          mobile: this.editUserInfoForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$msg.error('修改用户信息失败！')
        this.$msg.success('修改用户信息成功！')
        this.editUserInfoDialogVisible = false
        this.getUserList()
      })
    },
    async deleteUser (id) { // 删除用户
      const result = confirm('该操作将永久删除用户，是否确认删除！')
      if (!result) return
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('删除用户失败！')
      this.$msg.success('删除用户成功！')
      this.getUserList()
    },
    async showSetRoleDailog (role) { // 分配角色会话框
      this.setRole = role
      console.log(this.setRole)
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$msg.error('获取数据失败！')
      this.setRoleInfo = res.data
      this.setRloeDialogVisible = true
    },
    async setRloe () { // 点击修改按钮分配角色
      const { data: res } = await this.$http.put(`users/${this.setRole.id}/role`, { rid: this.selectedRoleId })
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('分配角色失败！')
      this.$msg.success('分配角色成功！')
      this.selectedRoleId = ''
      this.getUserList()
      this.setRloeDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
